﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using qna.Services;
using qna.Controls;
using qna.Business;
using System.Diagnostics;

namespace qna.pages
{
	public partial class AnswerQnA : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (Request.QueryString["view"] != null)
			{
				View(Convert.ToInt32(Request.QueryString["view"]));
				CreateAnsList(Convert.ToInt32(Request.QueryString["view"]));
				CreateAnswer1.IDquestion = Convert.ToInt32(Request.QueryString["view"]);
				CreateAnswer1.IDuser = Convert.ToInt32(User.Identity.Name);

			}

			else if (Request.QueryString["edit"] != null)
			{
				Edit(Convert.ToInt32(Request.QueryString["edit"]));
			}

			else if (Request.QueryString["delete"] != null)
			{
				Delete(Convert.ToInt32(Request.QueryString["delete"]));
			}

			else
			{
				Response.StatusCode = 404;
				TitlePage.Visible = true;
				TitlePage.InnerText = "Page Not Found";
				AnswersH2.Visible = false;
				CreateAnswer1.Visible = false;
				PostAnswer.Visible = false;
			}
			userId.Value = User.Identity.Name;
		}

		private void View(int id)
		{
			QuestionControl qc = (QuestionControl)LoadControl("~/Controls/QuestionControl.ascx");
			qc.Question = (Business.Question)(new QuestionService()).Get(id);
			QuestionPanel.Controls.Add(qc);
		}

		private void Edit(int id)
		{

			//There is an UpdateQuestion.aspx file in the pages folder. So, when the user clicks the btnEdit, the user will be redirected to that page and the QuestionControl will be added to that page.

			//todo authenticate
			//if (IsPostBack) {
			//    Response.Redirect("~/pages/Question.aspx?view=" + Request.QueryString["edit"]);
			//} else {
			//    QuestionForm qc = (QuestionForm)LoadControl("~/Controls/QuestionForm.ascx");
			//    qc.Question = (Business.Question)(new QuestionService()).Get(id);
			//    qc.Subjects = ((List<BusinessObject>)(new Subject()).GetAll()).ConvertAll<Subject>(delegate(BusinessObject bo) {
			//        return (Subject)bo;
			//    });
			//    panel.Controls.Add(qc);
			//}
		}

		private void Delete(int id)
		{
			//todo delete feature
		}


		private void CreateAnsList(int id)
		{
			AnswerService asc = new AnswerService();

			IList<Business.Answer> AnsList = asc.GetByQID(id);

			if (AnsList.Count == 0)
			{
				AnswersH2.Visible = false;
			}

			foreach (Business.Answer ans in AnsList)
			{
				AnswerControl ac = (AnswerControl)LoadControl("~/Controls/AnswerControl.ascx");

				ac.a = ans;
				AnswerList.Controls.Add(ac);
			}
		}
	}
}